package  
{
	import flash.events.MouseEvent;
	/**
	 * ...
	 * @author DarkGoodWIN
	 */
	public class TGlass extends TPictureControl
	{
		private var Ball: TBall = null;
		private var OrgY: int = 0;
		private var Log: TTextContainer;
		
		private var GlassInd: int = -1;
		
		public function HitTest(ax: int, any: int): Boolean
		{
			var B: Boolean = false; 
			if (ax > X)
			  if (ax < X + Width)
			    if (any > OrgY)
				  if (any < OrgY + Height)
				    B = true;
			return B;
		}
		
		private var InUp: Boolean = false;
		
		public function ToUp(): void
		{   
			InUp = true;
			Y = OrgY - 50;
			if (HitTest(Ball.X, Ball.Y))
			  Ball.State = TBall.StateOnUpperGlass;
		}
		
		public function ToDown(): void
		{
			var IsInUp: Boolean = InUp;
			InUp = false;
			Y = OrgY;
			if (HitTest(Ball.X, Ball.Y - 10))
			{
			  Ball.State = TBall.StateOnGlass;
			  if (IsInUp)
			    Ball.UpdateGlassIndToServer(GlassInd);
			}
		}
		
		public function CheckBall(ax: int, any: int): void
		{
			if (HitTest(ax, any))
			  ToUp()
			else
			  ToDown();
		}
		
		public function SetAlfa(DoSet: Boolean): void
		{
			  if (DoSet)
			  {
			    if (Ball.GameInfo.IsInHome())
			      Ctrl.alpha = 0.85;
			  }
			  else
			    Ctrl.alpha = 100;
		}
		
		public function DoPlaceBall(): void
		{
			Ctrl.alpha = 100; 
			Ball.X = Math.round(X + (Width - Ball.Width) / 2) + 2;
			Ball.Y = OrgY + Height - Ball.Height - 13;
			if (InUp)
			  Ball.State = TBall.StateOnUpperGlass;
			else
			{
			  Ball.State = TBall.StateOnGlass;			
			  SetAlfa(true);
			}
		}
		
		public function PlaceBall(ax: int, any: int): Boolean
		{
			if (!(HitTest(ax, any)))
			  return false;
			DoPlaceBall();
			return true;
		}
		
		private function DoWin(): void
		{
			Ball.GameInfo.Win();
			Ball.UpdateGlassIndToServer(-1);
		}
		
		private function DoLose(): void
		{
			Ball.GameInfo.Lose();
		}
		
		private function CheckBallInGlass(e: MouseEvent): void
		{
			if (Ball.GameInfo.Money <= 0)
			{
				new TModalMessage("В вашем кармане пусто");
				return;
			}
			if (Ball.State != TBall.StateOnGlass)
			  return;
		
			if (HitTest(Ball.X, Ball.Y))
				DoWin()
			else
				DoLose();
		}
		
		private function OnClick(e: MouseEvent): void
		{
			if (InUp)
			{	
				if (Ball.IsFriendBall)
					if (HitTest(Ball.X, Ball.Y))
						Ball.Return2Desk();
				ToDown()
			}
			else
			{
				if (Ball.IsFriendBall)
					CheckBallInGlass(e);
				ToUp();
			}
		}
		
		public function TGlass(Parent: TControl, x: int, y: int, aBall: TBall, aLog: TTextContainer, aGlassInd: int) 
		{
			super (res.glass, Parent, x, y);
			Ctrl.alpha = 100;
			GlassInd = aGlassInd;
			OrgY = y;
			Height = 180;
			Width = 120;
			Ball = aBall;
			Log = aLog;
			addEventListener(MouseEvent.CLICK, OnClick);
		}
		
	}

}